<?php
App::uses('AppController', 'Controller');
class ShopController extends AppController {

//////////////////////////////////////////////////

    public $components = array(
        'Cart',
        'Paypal',
        'AuthorizeNet'
    );

//////////////////////////////////////////////////

    public $uses = false;

//////////////////////////////////////////////////

    public function beforeFilter() {
        $this->Auth->allow('package_cart','package_address','package_step1','package_step2','package_review','add_to_cart','success');
        parent::beforeFilter();
        $this->disableCache();
        $this->Security->validatePost = false;
    }

//////////////////////////////////////////////////

    public function clear() {
        $this->Cart->clear();
        $this->Session->setFlash('All item(s) removed from your shopping cart', 'flash_error');
        return $this->redirect('/');
    }

//////////////////////////////////////////////////

    public function add() {
        if ($this->request->is('post')) {

            $id = $this->request->data['Product']['id'];

            $quantity = isset($this->request->data['Product']['quantity']) ? $this->request->data['Product']['quantity'] : null;

            $productmodId = isset($this->request->data['mods']) ? $this->request->data['mods'] : null;

            $product = $this->Cart->add($id, $quantity, $productmodId);
        }
        if(!empty($product)) {
            $this->Session->setFlash($product['Product']['name'] . ' was added to your shopping cart.', 'flash_success');
        } else {
            $this->Session->setFlash('Unable to add this product to your shopping cart.', 'flash_error');
        }
        $this->redirect($this->referer());
    }

//////////////////////////////////////////////////

    public function itemupdate() {
        if ($this->request->is('ajax')) {

            $id = $this->request->data['id'];

            $quantity = isset($this->request->data['quantity']) ? $this->request->data['quantity'] : null;

            if(isset($this->request->data['mods']) && ($this->request->data['mods'] > 0)) {
                $productmodId = $this->request->data['mods'];
            } else {
                $productmodId = null;
            }

            // echo $productmodId ;
            // die;

            $product = $this->Cart->add($id, $quantity, $productmodId);

        }
        $cart = $this->Session->read('Shop');
        echo json_encode($cart);
        $this->autoRender = false;
    }

//////////////////////////////////////////////////

    public function update() {
        $this->Cart->update($this->request->data['Product']['id'], 1);
    }

//////////////////////////////////////////////////

    public function remove($id = null) {
        $product = $this->Cart->remove($id);
        if(!empty($product)) {
            $this->Session->setFlash($product['Product']['name'] . ' was removed from your shopping cart', 'flash_error');
        }
        return $this->redirect(array('action' => 'cart'));
    }

//////////////////////////////////////////////////

    public function cartupdate() {
        if ($this->request->is('post')) {
            foreach($this->request->data['Product'] as $key => $value) {
                $p = explode('-', $key);
                $p = explode('_', $p[1]);
                $this->Cart->add($p[0], $value, $p[1]);
            }
            $this->Session->setFlash('Shopping Cart is updated.', 'flash_success');
        }
        return $this->redirect(array('action' => 'cart'));
    }

//////////////////////////////////////////////////

    public function cart() {
        $shop = $this->Session->read('Shop');
        $this->set(compact('shop'));
    }

//////////////////////////////////////////////////

    public function address() {

        $shop = $this->Session->read('Shop');
        if(!$shop['Order']['total']) {
            return $this->redirect('/');
        }

        if ($this->request->is('post')) {
            $this->loadModel('Order');
            $this->Order->set($this->request->data);
            if($this->Order->validates()) {
                $order = $this->request->data['Order'];
                $order['order_type'] = 'creditcard';
                $this->Session->write('Shop.Order', $order + $shop['Order']);
                return $this->redirect(array('action' => 'review'));
            } else {
                $this->Session->setFlash('The form could not be saved. Please, try again.', 'flash_error');
            }
        }
        if(!empty($shop['Order'])) {
            $this->request->data['Order'] = $shop['Order'];
        }

    }

//////////////////////////////////////////////////

    public function step1() {
        $paymentAmount = $this->Session->read('Shop');
        if(!$paymentAmount) {
            return $this->redirect('/');
        }
        $this->Session->write('Shop.Order.order_type', 'paypal');
        $this->Paypal->step1($paymentAmount);
    }

//////////////////////////////////////////////////

    public function step2() {

        $token = $this->request->query['token'];
        $paypal = $this->Paypal->GetShippingDetails($token);

        $ack = strtoupper($paypal['ACK']);
        if($ack == 'SUCCESS' || $ack == 'SUCESSWITHWARNING') {
            $this->Session->write('Shop.Paypal.Details', $paypal);
            return $this->redirect(array('action' => 'review'));
        } else {
            $ErrorCode = urldecode($paypal['L_ERRORCODE0']);
            $ErrorShortMsg = urldecode($paypal['L_SHORTMESSAGE0']);
            $ErrorLongMsg = urldecode($paypal['L_LONGMESSAGE0']);
            $ErrorSeverityCode = urldecode($paypal['L_SEVERITYCODE0']);
            echo 'GetExpressCheckoutDetails API call failed. ';
            echo 'Detailed Error Message: ' . $ErrorLongMsg;
            echo 'Short Error Message: ' . $ErrorShortMsg;
            echo 'Error Code: ' . $ErrorCode;
            echo 'Error Severity Code: ' . $ErrorSeverityCode;
            die();
        }

    }

//////////////////////////////////////////////////

    public function review() {

        $shop = $this->Session->read('Shop');

        if(empty($shop)) {
            return $this->redirect('/');
        }

        if ($this->request->is('post')) {

            $this->loadModel('Order');

            $this->Order->set($this->request->data);
            if($this->Order->validates()) {
                $order = $shop;
                $order['Order']['status'] = 1;

                if($shop['Order']['order_type'] == 'paypal') {
                    $paypal = $this->Paypal->ConfirmPayment($order['Order']['total']);
                    //debug($resArray);
                    $ack = strtoupper($paypal['ACK']);
                    if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING') {
                        $order['Order']['status'] = 2;
                    }
                    $order['Order']['authorization'] = $paypal['ACK'];
                    //$order['Order']['transaction'] = $paypal['PAYMENTINFO_0_TRANSACTIONID'];
                }

                if((Configure::read('Settings.AUTHORIZENET_ENABLED') == 1) && $shop['Order']['order_type'] == 'creditcard') {
                    $payment = array(
                        'creditcard_number' => $this->request->data['Order']['creditcard_number'],
                        'creditcard_month' => $this->request->data['Order']['creditcard_month'],
                        'creditcard_year' => $this->request->data['Order']['creditcard_year'],
                        'creditcard_code' => $this->request->data['Order']['creditcard_code'],
                    );
                    try {
                        $authorizeNet = $this->AuthorizeNet->charge($shop['Order'], $payment);
                    } catch(Exception $e) {
                        $this->Session->setFlash($e->getMessage());
                        return $this->redirect(array('action' => 'review'));
                    }
                    $order['Order']['authorization'] = $authorizeNet[4];
                    $order['Order']['transaction'] = $authorizeNet[6];
                }

                $save = $this->Order->saveAll($order, array('validate' => 'first'));
                if($save) {

                    $this->set(compact('shop'));

                    App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail();
                    $email->from(Configure::read('Settings.ADMIN_EMAIL'))
                            ->cc(Configure::read('Settings.ADMIN_EMAIL'))
                            ->to($shop['Order']['email'])
                            ->subject('Shop Order')
                            ->template('order')
                            ->emailFormat('text')
                            ->viewVars(array('shop' => $shop))
                            ->send();
                    return $this->redirect(array('action' => 'success'));
                } else {
                    $errors = $this->Order->invalidFields();
                    $this->set(compact('errors'));
                }
            }
        }

        if(($shop['Order']['order_type'] == 'paypal') && !empty($shop['Paypal']['Details'])) {
            $shop['Order']['first_name'] = $shop['Paypal']['Details']['FIRSTNAME'];
            $shop['Order']['last_name'] = $shop['Paypal']['Details']['LASTNAME'];
            $shop['Order']['email'] = $shop['Paypal']['Details']['EMAIL'];
            $shop['Order']['phone'] = '888-888-8888';
            $shop['Order']['billing_address'] = $shop['Paypal']['Details']['SHIPTOSTREET'];
            $shop['Order']['billing_address2'] = '';
            $shop['Order']['billing_city'] = $shop['Paypal']['Details']['SHIPTOCITY'];
            $shop['Order']['billing_zip'] = $shop['Paypal']['Details']['SHIPTOZIP'];
            $shop['Order']['billing_state'] = $shop['Paypal']['Details']['SHIPTOSTATE'];
            $shop['Order']['billing_country'] = $shop['Paypal']['Details']['SHIPTOCOUNTRYNAME'];

            $shop['Order']['shipping_address'] = $shop['Paypal']['Details']['SHIPTOSTREET'];
            $shop['Order']['shipping_address2'] = '';
            $shop['Order']['shipping_city'] = $shop['Paypal']['Details']['SHIPTOCITY'];
            $shop['Order']['shipping_zip'] = $shop['Paypal']['Details']['SHIPTOZIP'];
            $shop['Order']['shipping_state'] = $shop['Paypal']['Details']['SHIPTOSTATE'];
            $shop['Order']['shipping_country'] = $shop['Paypal']['Details']['SHIPTOCOUNTRYNAME'];

            $shop['Order']['order_type'] = 'paypal';

            $this->Session->write('Shop.Order', $shop['Order']);
        }

        $this->set(compact('shop'));

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////						Customer					//////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public function add_to_cart($id = null,$order_type	=	'paypal') {

		$this->Session->delete('Shop');
		$this->Loadmodel('Package');
		
		$this->request->onlyAllow('post', 'add_to_cart');
		$this->Package->id = $id;
		if (!$this->Package->exists()) {
			throw new NotFoundException(__('Invalid package'));
		}

		$options = array('conditions' => array('Package.' . $this->Package->primaryKey => $id));
		$package	=	 $this->Package->find('first', $options);
		$package['Package']['total']	=	$package['Package']['price'];

		if ($package) {
			$this->Session->write('Shop',$package);

		if($package['Package']['total'] > 0)			
        $this->Session->write('Shop.PackageOrder.order_type', $order_type);
		else
        $this->Session->write('Shop.PackageOrder.order_type', 'free');


		} else {
			$this->Session->setFlash(__('The package could not be added. Please, try again.'), 'error', array('class' => 'alert alert-danger'));
		}
		if($order_type=='paypal')
		return $this->redirect(array('controller'=>'Shop','action' => 'package_step1'));
		else
		return $this->redirect(array('controller'=>'Shop','action' => 'package_review'));
	}


    public function package_step1() {
        $this->Session->write('Shop.PackageOrder.order_type', 'paypal');

        $paymentAmount = $this->Session->read('Shop.Package.total');
        if(!$paymentAmount) {
//            return $this->redirect('/');
		return $this->redirect(array('controller'=>'Shop','action' => 'package_review'));
        }
          $this->Paypal->returnURL	=	Configure::read('Settings.WEBSITE') . '/shop/package_step2';
         $this->Paypal->cancelURL	=	Configure::read('Settings.WEBSITE') . '/packages/pricing';

        $this->Paypal->step1($paymentAmount);
    }

//////////////////////////////////////////////////

    public function package_step2() {

        $token = $this->request->query['token'];
        $paypal = $this->Paypal->GetShippingDetails($token);

        $ack = strtoupper($paypal['ACK']);
        if($ack == 'SUCCESS' || $ack == 'SUCESSWITHWARNING') {
            $this->Session->write('Shop.PackageOrder.Details', $paypal);
            return $this->redirect(array('action' => 'package_review'));
        } else {
            $ErrorCode = urldecode($paypal['L_ERRORCODE0']);
            $ErrorShortMsg = urldecode($paypal['L_SHORTMESSAGE0']);
            $ErrorLongMsg = urldecode($paypal['L_LONGMESSAGE0']);
            $ErrorSeverityCode = urldecode($paypal['L_SEVERITYCODE0']);
            echo 'GetExpressCheckoutDetails API call failed. ';
            echo 'Detailed Error Message: ' . $ErrorLongMsg;
            echo 'Short Error Message: ' . $ErrorShortMsg;
            echo 'Error Code: ' . $ErrorCode;
            echo 'Error Severity Code: ' . $ErrorSeverityCode;
            die();
        }

    }

//////////////////////////////////////////////////

public function package_address() {

        $shop = $this->Session->read('Shop');
        if(!$shop['Package']['total']) {
             return $this->redirect('/');
        }
        if ($this->request->is('post')) {
			
        if($shop['Package']['total']>0)
        $this->Session->write('Shop.PackageOrder.order_type', 'creditcard');
		else
        $this->Session->write('Shop.PackageOrder.order_type', 'free');
           
		   
		    return $this->redirect(array('action' => 'package_review'));
			
			}
        if(!empty($shop['Order'])) {
            $this->request->data['Order'] = $shop['Order'];
        }

    }

//////////////////////////////////////////////////
    public function package_review() {
        $shop = $this->Session->read('Shop');
//pr($shop);
			if($this->Session->read('Auth.User.expiry_date')){
				
				$expiry_date = strtotime($this->Session->read('Auth.User.expiry_date'));
				$current_date = strtotime(date('Y-m-d H:m'));
						if($current_date	<	$expiry_date)
						return $this->redirect(array('controller'=>'users','action'=>'edit_agent_profile'));
			}

        if(empty($shop['Package'])) {
            return $this->redirect(array('controller'=>'Packages','action'=>'pricing'));
        }



        if ($this->request->is('post')) {
            $this->loadModel('User');

		if($this->Session->read('Auth.User')){
		$this->request->data['User']['id']	=	$this->Session->read('Auth.User.id');
		}

            $this->User->set($this->request->data);
            if($this->User->validates()) {
                $order = $shop;
                $PackageOrder['PackageOrder']['status'] = 2;

                if(($shop['PackageOrder']['order_type'] == 'paypal') and ($order['Package']['total']>0)) {
                    $paypal = $this->Paypal->ConfirmPayment($order['Package']['total']);
                    //debug($resArray);
                    $ack = strtoupper($paypal['ACK']);
                    if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING') {
                        $PackageOrder['PackageOrder']['status']			 = '1';
                        $PackageOrder['PackageOrder']['order_type']		 = 'paypal';
						$PackageOrder['PackageOrder']['authorization']	 = $paypal['ACK'];
						$PackageOrder['PackageOrder']['TOKEN']			 = $shop['Paypal']['TOKEN'];
						$PackageOrder['PackageOrder']['payer_id'] 		 = $shop['Paypal']['payer_id'];
                     //$order['PackageOrder']['transaction'] = $paypal['PAYMENTINFO_0_TRANSACTIONID'];
					 }
                }

        if((Configure::read('Settings.AUTHORIZENET_ENABLED') == 1) && ($shop['PackageOrder']['order_type'] == 'creditcard') and ($order['Package']['total']>0)) {
                    $payment = array(
                        'creditcard_number' => $this->request->data['Order']['creditcard_number'],
                        'creditcard_month' => $this->request->data['Order']['creditcard_month'],
                        'creditcard_year' => $this->request->data['Order']['creditcard_year'],
                        'creditcard_code' => $this->request->data['Order']['creditcard_code'],
                    );
                    try {
                        $authorizeNet = $this->AuthorizeNet->charge($shop['Package'], $payment);
                        $PackageOrder['PackageOrder']['status'] = '1';
                        $PackageOrder['PackageOrder']['order_type'] = 'creditcard';
                    } catch(Exception $e) {
                        $this->Session->setFlash($e->getMessage(),'error');
                        return $this->redirect(array('action' => 'package_review'));
                    }
                    $PackageOrder['PackageOrder']['authorization']  = $authorizeNet[4];
                    $PackageOrder['PackageOrder']['transaction'] 	= $authorizeNet[6];
                }

				if(($order['Package']['total']==0)) {
				$PackageOrder['PackageOrder']['order_type'] = 'free';
				$PackageOrder['PackageOrder']['status'] 	= '1';
				}

				if(($PackageOrder['PackageOrder']['status']==1)){
					

				$total_months	=	$shop['Package']['months'];
				$NewDateExpired	=	Date('Y-m-d H:i', strtotime("+$total_months months"));
				

				$this->request->data['User']['expiry_date']	=	$NewDateExpired;

/*				if($shop['Package']['price']>0)
				$this->request->data['User']['approved']	=	1;
				else
				$this->request->data['User']['approved']	=	0;
*/

				if(!$this->Session->read('Auth.User.id'))
				$this->request->data['User']['approved']	=	0;

                $save = $this->User->save($this->request->data['User'], array('validate' => 'first'));
                if($save) {
           			 $this->loadModel('PackageOrder');
					if($this->Session->read('Auth.User')){
						$this->Session->write('Auth.User.expiry_date',$NewDateExpired);
					}
		
		
					if(($this->request->data['User']['id']) and !empty($this->request->data['User']['id']))
					$getLastInsertID	=	$this->request->data['User']['id'];
					else
					$getLastInsertID	=	$this->User->getLastInsertID();
                   
				   
				    $PackageOrder['PackageOrder']['user_id'] 	= 	$getLastInsertID;
                    $PackageOrder['PackageOrder']['package_id'] = 	$shop['Package']['id'];
                    $PackageOrder['PackageOrder']['title'] 		= 	$shop['Package']['title'];
                    $PackageOrder['PackageOrder']['months'] 	= 	$shop['Package']['months'];
                    $PackageOrder['PackageOrder']['expierd'] 	= 	$NewDateExpired;
					
                if($this->PackageOrder->save($PackageOrder));
                    $this->set(compact('shop'));
				$this->Session->setFlash(__('You have successfully complated your  package payment proccess. Please check your account.'), 'default', array('class' => 'alert alert-success'));
				$this->Session->delete('Shop');
				
				return $this->redirect(array('action' => 'success'));
                    
					App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail();
                    $email->from(Configure::read('Settings.ADMIN_EMAIL'))
                            ->cc(Configure::read('Settings.ADMIN_EMAIL'))
                            ->to($shop['User']['email'])
                            ->subject('Get Register')
                            ->template('order')
                            ->emailFormat('text')
                            ->viewVars(array('shop' => $shop))
                            ->send();
                    return $this->redirect(array('action' => 'success'));
                } 
				}else {
                    $errors = $this->User->invalidFields();
                    $this->set(compact('errors'));
                }
            }
        }

        if(($shop['PackageOrder']['order_type'] == 'paypal') && !empty($shop['Paypal']['Details'])) {
            $shop['Order']['first_name'] = $shop['Paypal']['Details']['FIRSTNAME'];
            $shop['Order']['last_name'] = $shop['Paypal']['Details']['LASTNAME'];
            $shop['Order']['email'] = $shop['Paypal']['Details']['EMAIL'];
            $shop['Order']['billing_address'] = $shop['Paypal']['Details']['SHIPTOSTREET'];
            $shop['Order']['billing_address2'] = '';
            $shop['Order']['billing_city'] = $shop['Paypal']['Details']['SHIPTOCITY'];
            $shop['Order']['billing_zip'] = $shop['Paypal']['Details']['SHIPTOZIP'];
            $shop['Order']['billing_state'] = $shop['Paypal']['Details']['SHIPTOSTATE'];
            $shop['Order']['billing_country'] = $shop['Paypal']['Details']['SHIPTOCOUNTRYNAME'];

            $shop['Order']['shipping_address'] = $shop['Paypal']['Details']['SHIPTOSTREET'];
            $shop['Order']['shipping_address2'] = '';
            $shop['Order']['shipping_city'] = $shop['Paypal']['Details']['SHIPTOCITY'];
            $shop['Order']['shipping_zip'] = $shop['Paypal']['Details']['SHIPTOZIP'];
            $shop['Order']['shipping_state'] = $shop['Paypal']['Details']['SHIPTOSTATE'];
            $shop['Order']['shipping_country'] = $shop['Paypal']['Details']['SHIPTOCOUNTRYNAME'];

            $shop['Order']['order_type'] = 'paypal';

         //   $this->Session->write('Shop.Order', $shop['Order']);
        }
        $this->set(compact('shop'));

    }

//////////////////////////////////////////////////

    public function success() {
		$this->Session->delete('Shop');
        $shop = $this->Session->read('Shop');
        //$this->Cart->clear();
        if(empty($shop)) {
						return $this->redirect(array('controller'=>'users','action'=>'edit_agent_profile'));
        }
        $this->set(compact('shop'));
    }

//////////////////////////////////////////////////

}
